//
//  VRApplyTestViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/18.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRApplyTestViewController.h"
#import "VRTestingViewController.h"

#import "XDropMenuView.h"

@interface VRApplyTestViewController () <XDropMenuViewDelegate, UITextViewDelegate>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *nameLbl;
@property (nonatomic, strong) UILabel *mobileLbl;
@property (nonatomic, strong) UILabel *placeholderLbl;
@property (nonatomic, strong) UITextView *editTextView;
@property (nonatomic, strong) XDropMenuView *dropMenu;

@property (nonatomic, strong) NSArray *homeAddressArray;
@property (nonatomic, copy) NSString *class0;

@end

@implementation VRApplyTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"设备测试";
    
    [self setupSubView];
    [self setupListMenu];
    [self getHomeAddress];
}

- (void)setupSubView
{
    
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    self.contentView = contentView;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.view);
    }];
    
    UILabel *nameLbl = [[UILabel alloc] init];
    nameLbl.text = [NSString stringWithFormat:@"姓名：%@", self.nameStr];
    nameLbl.textColor = RGB(120, 120, 120);
    nameLbl.font = VRFont(16);
    [contentView addSubview:nameLbl];
    self.nameLbl = nameLbl;
    [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(80);
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    UILabel *mobileLbl = [[UILabel alloc] init];
    mobileLbl.text = [NSString stringWithFormat:@"电话：%@", self.mobile];;
    mobileLbl.textColor = RGB(120, 120, 120);
    mobileLbl.font = VRFont(16);
    [contentView addSubview:mobileLbl];
    self.mobileLbl = mobileLbl;
    [mobileLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(nameLbl.mas_bottom).offset(16);
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 150);
    [contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(mobileLbl.mas_bottom).offset(16);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(180);
    }];
    
    UIImageView *iconImgView = [[UIImageView alloc] init];
    iconImgView.image = [UIImage imageNamed:@"check_log"];
    iconImgView.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(14);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.numberOfLines = 0;
    titleLbl.textColor = MAINColor;
    titleLbl.font = VRFont(16);
    titleLbl.text = @"备注";
    [bgView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iconImgView.mas_right).offset(4);
        make.centerY.mas_equalTo(iconImgView);
    }];
    
    // 创建textview
    UITextView *textView = [[UITextView alloc] init];
    textView.backgroundColor = [UIColor whiteColor];
    textView.font = VRFont(15);
    textView.delegate = self;
    textView.frame = CGRectMake(20, 40, kScreenWidth - 40, 140);
    self.editTextView = textView;
    [bgView addSubview:textView];
    
    NSString *placeholderStr = [NSString stringWithFormat:@"填写备注信息"];
    UILabel *placeholderLbl = [[UILabel alloc] init];
    placeholderLbl.numberOfLines = 0;
    placeholderLbl.textColor = RGB(180, 180, 180);
    placeholderLbl.font = VRFont(15);
    placeholderLbl.text = placeholderStr;
    //    textView.text
    CGSize placeholderSize = [placeholderStr sizewithFont:placeholderLbl.font maxSize:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
    [textView addSubview:placeholderLbl];
    self.placeholderLbl = placeholderLbl;
    placeholderLbl.frame = CGRectMake(4, 8, placeholderSize.width + 4, placeholderSize.height);
    
    
    UILabel *tipLbl = [[UILabel alloc] init];
    tipLbl.numberOfLines = 0;
    tipLbl.textColor = MAINColor;
    tipLbl.font = VRFont(12);
    tipLbl.text = @"*本测试共计15分钟，报警内容全部默认为误报信息，望业主悉知。";
    [contentView addSubview:tipLbl];
    [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(bgView.mas_bottom).offset(8);
    }];
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.backgroundColor = RGB(78, 173, 57);
    saveBtn.layer.cornerRadius = 4;
    [saveBtn setTitle:@"提交" forState:UIControlStateNormal];
    saveBtn.titleLabel.font = VRFont(16);
    [saveBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [saveBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(contentView);
        make.top.mas_equalTo(bgView.mas_bottom).offset(60);
        make.width.mas_equalTo(290);
        make.height.mas_equalTo(40);
    }];
}


- (void)setupListMenu
{
    
    UIView *listBgView = [[UIView alloc] init];
//    listBgView.backgroundColor = RGB(255, 255, 255);
    listBgView.frame = CGRectMake(0, 0, kScreenWidth, 80);
    [self.contentView addSubview:listBgView];
    [self.contentView bringSubviewToFront:listBgView];
    
    UIView *listView = [[UIView alloc] init];
    listView.backgroundColor = RGB(255, 255, 255);
    listView.layer.borderColor = MAINColor.CGColor;
    listView.layer.borderWidth = 1.0;
    listView.frame = CGRectMake(0, 0, kScreenWidth - 20 * 2, 40);
    listView.center = CGPointMake(kScreenWidth * 0.5, 40);
    [listBgView addSubview:listView];
    
    //列表展示的模型
    NSMutableArray *section1Datas = [NSMutableArray array];
    
    //    NSArray *title1Array = @[@"智慧烟感监测", @"智慧气感监测"];
    //    for (NSString *str in title1Array) {
    //        XMenuModel *model = [[XMenuModel alloc] init];
    //        model.name = str;
    //        model.id = 0;
    //        [section1Datas addObject:model];
    //    }
    
    NSMutableArray *allDatas = [NSMutableArray array];
    [allDatas addObject:section1Datas];
    
    //上边按钮展示的模型,此模型对text赋值即可.
    NSArray *titleArray = @[@"选择所属小区单元"];
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    XDropMenuView *dropMenu = [[XDropMenuView alloc] initWithFrame:CGRectMake(0, 0, listView.width, 40) showOnView:self.view AllDataArr:allDatas showArr:[titleArray copy]];
    dropMenu.itemNormalColor = MAINColor;
    dropMenu.itemSelectedColor = MAINColor;
    dropMenu.titleNormalColor = MAINColor;
    dropMenu.titleSelectedColor = MAINColor;
    dropMenu.fonteSize = 14;
    dropMenu.delegate = self;
    [listView addSubview:dropMenu];
    self.dropMenu = dropMenu;
    
}


#pragma mark - networking
- (void)getHomeAddress
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    hud.bezelView.backgroundColor = RGBA(0, 0, 0, 0.9);
    //    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:GetHomeAddress parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            //            self.deviceDataModelArray = [VRDeviceDataModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            self.homeAddressArray = responseObject[@"data"];
            NSMutableArray *section1Datas = [NSMutableArray array];
            NSArray *dictArray = responseObject[@"data"];
            for (NSDictionary *dict in dictArray) {
                
                XMenuModel *model = [[XMenuModel alloc] init];
                model.name = dict[@"address"];
                model.id = dict[@"fID"];
                [section1Datas addObject:model];
            }
            NSMutableArray *allDatas = [NSMutableArray array];
            [allDatas addObject:section1Datas];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.dropMenu.AllDataArr = allDatas;
                if (section1Datas.count > 0) {
                    [self.dropMenu selectClum:0 Row:0];
                    self.class0 = ((XMenuModel *)([section1Datas firstObject])).id;
                }
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}

- (void)saveTestInfo
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"fID"] = self.class0;
    param[@"remark"] = self.editTextView.text;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:PutTest parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
//                [self.navigationController popViewControllerAnimated:YES];
                VRTestingViewController *testingVc = [[VRTestingViewController alloc] init];
                testingVc.fID = self.class0;
                [self.navigationController pushViewController:testingVc animated:YES];
            });
            
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}

#pragma mark - action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)onSaveBtnClick:(UIButton *)sender
{
    if (self.editTextView.text.length < 10) {
        [SVProgressHUD showErrorWithStatus:@"请输入10个字以上的描述"];
        return;
    }
    if (self.homeAddressArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"您暂时没有住宅信息"];
        return;
    }
    if (self.class0 == nil) {
        [SVProgressHUD showErrorWithStatus:@"您暂时没有住宅信息"];
        return;
    }
    [self saveTestInfo];
    
    
}


#pragma mark - Delegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        self.placeholderLbl.hidden = YES;
    }else{
        self.placeholderLbl.hidden = NO;
    }
}


#pragma mark - XDropMenuViewDelegate
- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectColum:(NSInteger)colum
{
    [self.view endEditing:YES];
}

- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectRowAtColum:(NSInteger)colum Row:(NSInteger)row model:(XMenuModel *)model
{
    self.class0 = model.id;
}

@end
